'use stirct';

let fs = require('fs');
let path = require('path');
let router = require('koa-router')();

function search(dir) {
    let flies = fs.readdirSync(dir);
    let filter = flies.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    })
    return filter;
}

function getforEach(flies) {
    flies.forEach(item => {
        let tmpflies = path.join(__dirname, item);
        let tmprouter = require(tmpflies);
        for (var x in tmprouter) {
            let type = tmprouter[x][0];
            let fn = tmprouter[x][1];

            if (type === 'get') {
                router.get(x, fn)
            } else {
                router.post(x, fn)
            }
        }
    })
}

module.exports = function () {
    let constrollerDir = __dirname;
    let constrollerFlies = search(constrollerDir);
    getforEach(constrollerFlies);
    return router.routes();
}